package com.bidianying.service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import redis.clients.jedis.ShardedJedisPool;

import com.bidianying.dao.CommonDao;
import com.bidianying.util.JsonUtil;
import com.bidianying.util.RedisUtils;


@Service
public class CommonService {
	
	@Autowired
	private CommonDao commonDao;
	@Autowired
	private RestTemplate restTemplate;
	@Autowired
	private ShardedJedisPool shardedJedisPool;
	
	
	public void saveMaizuoCinemaForRedis(){
	}
	
	//根据一部电影的排期来比较是不是属于同一个影院
	public void compareCinemaForMaizuoGewala(){
		List<Map<String,String>> maizuoCinemaList = commonDao.getAllMaizuoCinemaInfo();
		List<Map<String,String>> gewaraCinemaList = commonDao.getAllGewaraCinemaInfo();
		List<Map<String,String>> movieInfoList = commonDao.getAllCinemaInfo();
		movieInfoList = movieInfoList.subList(0, 3);
		List<Map<String,String>> resultList = new ArrayList<Map<String,String>>();
		Set<String> sameIdSet = new HashSet<String>();
		Set<String> fyrq = new HashSet<String>();
		fyrq.add("2015-07-11");
		fyrq.add("2015-07-12");
		String dateFlag = "1";
		for(String fyrqStr : fyrq){
			if(fyrqStr.equals("2015-07-11")){
				dateFlag = "1";
			}
			if(fyrqStr.equals("2015-07-12")){
				dateFlag = "2";
			}
			for(Map<String,String> movieInfoMap : movieInfoList){
				System.out.println("比较电影----"+movieInfoMap.get("movieName"));
				String gewaraMovieId = movieInfoMap.get("gewaraMovieId");
				String maizuoMovieId = movieInfoMap.get("maizuoMovieId");
				if(gewaraMovieId==null || maizuoMovieId==null){
					continue;		
				}
				maizuoMovieId = String.valueOf(Integer.parseInt(maizuoMovieId)-100000000);
				Map<String,String> gewaraMap = new HashMap<String,String>();
				Map<String,String> maizuoMap = new HashMap<String,String>();
				for(Map<String,String> map : gewaraCinemaList){
					String cityPinyin = map.get("cityPinyin");
					if(cityPinyin.equals("shenzhen")){
						continue;
					}
					System.out.println("循环城市---影院---"+cityPinyin+"--"+map.get("title"));
					String cinemaCode = map.get("cinemaCode");
					String url = "http://www.gewara.com/movie/ajax/getOpiItem.xhtml?movieid="+gewaraMovieId+"&fyrq="+fyrqStr+"&cid="+cinemaCode;
					System.out.println("url====="+url);
					try {
						Document doc = Jsoup.connect(url).get();
						Element chooseOpi_body = doc.getElementsByClass("chooseOpi_body").first();
						if(chooseOpi_body==null){
							continue;
						}
						Elements li = chooseOpi_body.select("li");
						StringBuffer sb = new StringBuffer();
						for(Element ele : li){
							String str = ele.select(".opitime").first().select("b").first().text();
							sb.append(str+"_");
						}
						String fysj = sb.toString().substring(0, sb.toString().length()-1);
						System.out.println("fysj---"+fysj);
						Thread.sleep(1000);
						gewaraMap.put(cityPinyin+"__"+fysj, cinemaCode+"_"+map.get("title"));
					} catch (Exception e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
				for(Map<String,String> map : maizuoCinemaList){
					String cinemaId = map.get("cinemaId");
					String cityId = map.get("cityId");
					String cityPinyin = map.get("cityPinyin").toLowerCase();
					String name = map.get("name");
					if(cityPinyin.equals("shenzhen")){
						continue;
					}
					System.out.println("卖座循环城市---影院---"+cityPinyin+"--"+name);
					String url = "http://www.maizuo.com/seat/showCinemaForeTells.htm?cinemaId="+cinemaId+"&cityId="+cityId+"&dateFlag="+dateFlag;
					System.out.println("url====="+url);
					String str = restTemplate.getForObject(url, String.class);
					JSONObject jsonObject = JSONObject.fromObject(str);
					if(jsonObject.getInt("status")!=0){
						continue;
					}
					JSONArray jsonArray = jsonObject.getJSONObject("data").getJSONArray("foretells");
					StringBuffer sb = new StringBuffer();
					for(int i = 0;i<jsonArray.size();i++){
						JSONObject obj = jsonArray.getJSONObject(i);
						if(obj.getInt("filmId")==Integer.parseInt(maizuoMovieId)){
							String showtime = obj.getString("showtime");
							sb.append(showtime.substring(0, 2)+":"+showtime.substring(2, 4)+"_");
						}
					}
					if(sb.toString().length()==0){
						continue;
					}
					String fysj = sb.toString().substring(0, sb.toString().length()-1);
					System.out.println("fysj---"+fysj);
					try {
						Thread.sleep(1000);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
					maizuoMap.put(cityPinyin+"__"+fysj, cinemaId+"_"+name);
				}
				
				Set<String> keySet = gewaraMap.keySet();
				Set<String> keySetMaizuo = maizuoMap.keySet();
				for(String key : keySet){
					String[] keyArray = key.split("__");
					for(String keyMaizuo : keySetMaizuo){
						String[] keyMaizuoArray = keyMaizuo.split("__");
						if(keyArray[0].equals(keyMaizuoArray[0])){
							if(keyMaizuoArray[1].equals(keyArray[1])){//说明同一个影院
								String cinemaId = gewaraMap.get(key).split("_")[0]; 
								if(!sameIdSet.contains(cinemaId)){
									sameIdSet.add(cinemaId);
									Map<String,String> map = new HashMap<String,String>();
									map.put("gewaraId", gewaraMap.get(key).split("_")[0]);
									map.put("gewaraName", gewaraMap.get(key).split("_")[1]);
									map.put("maizuoId", maizuoMap.get(keyMaizuo).split("_")[0]);
									map.put("maizuoName", maizuoMap.get(keyMaizuo).split("_")[1]);
									resultList.add(map);
									System.out.println("相同的影院---gewara--"+gewaraMap.get(key)+"--maizuo--"+maizuoMap.get(keyMaizuo));
									System.out.println("gewara---"+keyArray[1]);
									System.out.println("maizuo---"+keyMaizuoArray[1]);
								}
							}
						}
					}
				}
			}
		}
		for(Map<String,String> map : gewaraCinemaList){
			if(map.get("cityPinyin").equals("shenzhen")){
				continue;
			}
			String title = map.get("title");
			String cinemaId = map.get("cinemaCode");
			for(Map<String,String>  maizuoMap : maizuoCinemaList){
				String name = maizuoMap.get("name");
				if(title.equals(name)){
					if(!sameIdSet.contains(cinemaId)){
						sameIdSet.add(cinemaId);
						Map<String,String> mapTemp = new HashMap<String,String>();
						mapTemp.put("gewaraId", map.get("cinemaCode"));
						mapTemp.put("gewaraName", map.get("title"));
						mapTemp.put("maizuoId", maizuoMap.get("cinemaId"));
						mapTemp.put("maizuoName", maizuoMap.get("name"));
						resultList.add(mapTemp);
					}
				}
			}
		}
		System.out.println("相同影院的个数-----"+resultList.size());
		for(Map<String,String> map :resultList){
			System.out.println("gewara---"+map.get("gewaraId")+"-"+map.get("gewaraName")+"--maizuo---"+map.get("maizuoId")+"-"+map.get("maizuoName"));
		}
		commonDao.updateCinemaForMaizuo(resultList);
	}
	
	//比较插入淘宝的影院信息
	public void updateCinemaForTaobao(){
		List<Map<String,String>> taobaoCinemaList = commonDao.getAllTaobaoCinemaInfo();
		List<Map<String,String>> gewaraCinemaList = commonDao.getAllGewaraCinemaInfo();
		List<Map<String,String>> movieInfoList = commonDao.getAllCinemaInfo();
		movieInfoList = movieInfoList.subList(0, 3);
		List<Map<String,String>> resultList = new ArrayList<Map<String,String>>();
		Set<String> sameIdSet = new HashSet<String>();
		Set<String> fyrq = new HashSet<String>();
		fyrq.add("2015-07-16");
		for(String fyrqStr : fyrq){
			for(Map<String,String> movieInfoMap : movieInfoList){
				System.out.println("比较电影----"+movieInfoMap.get("movieName"));
				String gewaraMovieId = movieInfoMap.get("gewaraMovieId");
				String taobaoMovieId = movieInfoMap.get("taobaoMovieId");
				Map<String,String> gewaraMap = new HashMap<String,String>();
				Map<String,String> taobaoMap = new HashMap<String,String>();
				for(Map<String,String> map : gewaraCinemaList){
					String cityPinyin = map.get("cityPinyin");
					if(!cityPinyin.equals("beijing")){
						continue;
					}
					System.out.println("循环城市---影院---"+cityPinyin+"--"+map.get("title"));
					String cinemaCode = map.get("cinemaCode");
					String url = "http://www.gewara.com/movie/ajax/getOpiItem.xhtml?movieid="+gewaraMovieId+"&fyrq="+fyrqStr+"&cid="+cinemaCode;
					System.out.println("url====="+url);
					try {
						Document doc = Jsoup.connect(url).get();
						Element chooseOpi_body = doc.getElementsByClass("chooseOpi_body").first();
						
						Thread.sleep(500);		
						
						if(chooseOpi_body==null){
							continue;
						}
						Elements li = chooseOpi_body.select("li");
						StringBuffer sb = new StringBuffer();
						for(Element ele : li){
							String str = ele.select(".opitime").first().select("b").first().text();
							sb.append(str+"_");
						}
						String fysj = sb.toString().substring(0, sb.toString().length()-1);
						System.out.println("fysj---"+fysj);
						gewaraMap.put(cityPinyin+"__"+fysj, cinemaCode+"_"+map.get("title"));
					} catch (Exception e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
				for(Map<String,String> map : taobaoCinemaList){
					String cinemaId = map.get("cinemaId");
					String cityPinyin = map.get("cityPinyin").toLowerCase();
					String cinemaName = map.get("cinemaName");
					if(!cityPinyin.equals("beijing")){
						continue;
					}
					System.out.println("淘宝循环城市---影院---"+cityPinyin+"--"+cinemaName);
					String url = "http://dianying.taobao.com/cinemaDetailSchedule.htm?cinemaId="+cinemaId+"&activityId=&fCode=&showId="+taobaoMovieId+"&showDate="+fyrqStr+"&n_s=new";
					HttpHeaders requestHeaders = new HttpHeaders();  
					requestHeaders.set("Accept-Charset", "utf-8");  
					requestHeaders.set("Content-type", "text/xml; charset=utf-8");
					HttpEntity<String> entity = new HttpEntity<String>(null, requestHeaders);
					ResponseEntity<String> resultStr = restTemplate.exchange(url, HttpMethod.GET, entity, String.class);
					
					try {
						Thread.sleep(500);
					} catch (InterruptedException e1) {
						e1.printStackTrace();
					}	
					
					if(resultStr.getStatusCode().value() != 200){
						continue;
					}
					if(resultStr.getBody() == null){
						continue;
					}
					Document doc = Jsoup.parse(resultStr.getBody());
					if(doc == null){
						continue;
					}
					Element table = doc.select("table").first();
					if(table == null){
						continue;
					}
					Elements tr = table.select("tr");
					StringBuffer sb = new StringBuffer();
					for(Element ele : tr){
						String str = ele.select(".hall-time").first().select("em").text();
						if(!str.equals("")){
							sb.append(str+"_");
						}
					}
					String fysj = sb.toString().substring(0, sb.toString().length()-1);
					System.out.println("fysj---"+fysj);
					try {
						Thread.sleep(1000);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
					taobaoMap.put(cityPinyin+"__"+fysj, cinemaId+"_"+cinemaName);
				}
				
				Set<String> keySet = gewaraMap.keySet();
				Set<String> keySetTaobao = taobaoMap.keySet();
				for(String key : keySet){
					String[] keyArray = key.split("__");
					for(String keyTaobao : keySetTaobao){
						String[] keyTaobaoArray = keyTaobao.split("__");
						if(keyArray[0].equals(keyTaobaoArray[0])){
							if(keyTaobaoArray[1].equals(keyArray[1])){//说明同一个影院
								String cinemaId = gewaraMap.get(key).split("_")[0]; 
								if(!sameIdSet.contains(cinemaId)){
									sameIdSet.add(cinemaId);
									Map<String,String> map = new HashMap<String,String>();
									map.put("gewaraId", gewaraMap.get(key).split("_")[0]);
									map.put("gewaraName", gewaraMap.get(key).split("_")[1]);
									map.put("taobaoId", taobaoMap.get(keyTaobao).split("_")[0]);
									map.put("taobaoName", taobaoMap.get(keyTaobao).split("_")[1]);
									resultList.add(map);
									System.out.println("相同的影院---gewara--"+gewaraMap.get(key)+"--maizuo--"+taobaoMap.get(keyTaobao));
									System.out.println("gewara---"+keyArray[1]);
									System.out.println("maizuo---"+keyTaobaoArray[1]);
								}
							}
						}
					}
				}
			}
		}
		
		for(Map<String,String> map : gewaraCinemaList){
			if(!map.get("cityPinyin").equals("beijing")){
				continue;
			}
			String title = map.get("title");
			String cinemaId = map.get("cinemaCode");
			for(Map<String,String>  taobaoMap : taobaoCinemaList){
				String cinemaName = taobaoMap.get("cinemaName");
				if(title.equals(cinemaName)){
					if(!sameIdSet.contains(cinemaId)){
						sameIdSet.add(cinemaId);
						Map<String,String> mapTemp = new HashMap<String,String>();
						mapTemp.put("gewaraId", map.get("cinemaCode"));
						mapTemp.put("gewaraName", map.get("title"));
						mapTemp.put("taobaoId", taobaoMap.get("cinemaId"));
						mapTemp.put("taobaoName", taobaoMap.get("cinemaName"));
						resultList.add(mapTemp);
					}
				}
			}
		}
		System.out.println("相同影院的个数-----"+resultList.size());
		for(Map<String,String> map :resultList){
			System.out.println("gewara---"+map.get("gewaraId")+"-"+map.get("gewaraName")+"--maizuo---"+map.get("taobaoId")+"-"+map.get("taobaoName"));
		}
		Map<String,String> redisMap = new HashMap<String,String>();
		redisMap.put("taobaoCinemaInfo", JsonUtil.toJSON(resultList));
		RedisUtils.hmset(shardedJedisPool, "taobaoCinemaInfo", redisMap, 0);
		
		commonDao.updateCinemaForTaobao(resultList);
	}
	
	@SuppressWarnings("unchecked")
	public void updateCinemaForTaobaoFromRedis(){
		String taobaoCinemaInfo =  RedisUtils.hget(shardedJedisPool, "taobaoCinemaInfo", "taobaoCinemaInfo");
		JSONArray resultJson = JSONArray.fromObject(taobaoCinemaInfo);
		commonDao.updateCinemaForTaobao(resultJson);
	}
	
	
	public Map<String,Object> getCinemaMapByCinemaId(String cinemaId){
		return commonDao.getCinemaMapByCinemaId(cinemaId);
	}
	
	public Map<String,Object> getMovieMapByMovieId(String cinemaId){
		return commonDao.getMovieMapByMovieId(cinemaId);
	}
	
	public Map<String,String> getAllCinemaInfoForRedis(){
		return commonDao.getAllCinemaInfoForRedis();
	}
	public Map<String,String> getAllMovieForRedis(){
		return commonDao.getAllMovieForRedis();
	}
}
